<template>
  <div class="login-page">
    <div class="login-container">
      <h2 class="title">template</h2>
      <h2 class="title">登录</h2>
      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="80px"
        class="login-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            placeholder="请输入密码"
            show-password
          ></el-input>
        </el-form-item>
        <!-- 滑块验证码 -->
        <el-form-item v-if="isSlideEnabled" label="验证码" prop="slideVerify">
          <PuzzleCode
            v-model:complete="form.slideVerify"
            :canvas-width="300"
            :canvas-height="160"
            :slider-size="40"
            :border-radius="8"
            success-text="验证成功！"
            fail-text="验证失败，请重试"
            slider-text="请拖动滑块完成验证"
            @success="handleSlideSuccess"
            @fail="handleSlideFail"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login-btn" @click="onSubmit">
            登录
          </el-button>
        </el-form-item>
      </el-form>
      <div class="footer">
        还没有账号？<el-button @click="goToRegister">立即注册</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { login } from '@/api/User.js'
import { getStorage, setStorage } from '@/utils/storage.js'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import useUserStore from '@/store/user.js'
import { getCurrentInstance,ref } from 'vue';
import PuzzleCode from '@/components/PuzzleCode.vue'

// 是否启用滑块验证
const isSlideEnabled = import.meta.env.VITE_LOGIN_SLIDE_ENABLED === 'true'

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const {proxy} = getCurrentInstance();


const form = ref({
  username: "",
  password: ""
});

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 滑块验证成功回调
const handleSlideSuccess = (x) => {
  form.value.slideVerify = true
  ElMessage.success('验证成功')
}

// 滑块验证失败回调
const handleSlideFail = (x) => {
  form.value.slideVerify = false
  ElMessage.warning('验证失败，请重试')
}

const onSubmit = () => {
  proxy.$refs.formRef.validate(valid => {
    if (valid) {
      // 如果启用了滑块验证但未通过验证，则提示用户
      if (isSlideEnabled && !form.value.slideVerify) {
        ElMessage.warning('请完成滑块验证')
        return
      }

      login(form.value).then(res => {
        if (res.code === 1) {
          setStorage('TOKEN', res.data.accessToken)
          setStorage('REFRESH_TOKEN', res.data.refreshToken)
          ElMessage({
            message: res.msg,
            type: 'success'
          })
          userStore.getUserInfo().then(() => {
            router.push({ path: '/' })
          })
        } else {
          if (isSlideEnabled) {
            // 登录失败时重置滑块验证
            proxy.$refs.formRef.clearValidate('slideVerify')
            form.value.slideVerify = false
          }
        }
      })
    }
  })
}

const goToRegister = () => {
  router.push('/register')
}
</script>

<style scoped lang="scss">
.login-page {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-image: url('@/assets/images/login.jpeg');
  background-size: cover;
  background-position: center;
}

.login-container {
  width: 360px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.login-form {
  margin-top: 10px;
}

.login-btn {
  width: 100%;
}

.footer {
  margin-top: 20px;
  font-size: 14px;
  color: #666;
}

.register-link {
  color: #409eff;
  text-decoration: none;
}
</style>
